package com.rw.coco.handler;

import com.rw.coco.api.data.CocoDataApi;
import com.rw.coco.api.data.PersistenceMapper;
import com.rw.coco.api.data.TransactionSwitch;
import com.rw.coco.api.data.model.AccountModel;
import com.rw.coco.api.data.persistence.AccountMapper;
import com.rw.coco.api.data.persistence.GroupMapper;
import com.rw.coco.api.log.CocoLogger;
import com.rw.coco.api.modle.Account;
import com.rw.coco.api.modle.Bot;
import com.rw.coco.api.modle.Group;
import com.rw.coco.util.CocoData;
import com.rw.coco.util.TransactionUtil;
import com.rw.tool.util.string.StringFormatter;

/**
 * 群非法操作
 */
public abstract class GroupIllegalHandler {

    protected final CocoDataApi dataApi;

    protected final CocoLogger cocologger;

    protected final CocoData cocoData;

    protected GroupIllegalHandler(CocoDataApi dataApi, CocoLogger cocologger, CocoData cocoData) {
        this.dataApi = dataApi;
        this.cocologger = cocologger;
        this.cocoData = cocoData;
    }

    /**
     * 封禁群以及操作者
     *
     * @param msg     封禁信息
     * @param account 操作者信息
     * @param group   被封禁群聊信息
     * @param bot     机器人信息
     */
    protected void banGroupAndAccount(String msg, Account account, Group group, Bot bot, AccountModel accountModel) {
        // 输出日志
        String info = StringFormatter.format(msg, bot.getName(), bot.getId(), group.getName(), group.getId(),
                account.getNick(), account.getId());

        // 如果操作者是超级管理员，则不作操作
        if (accountModel.getSuperAdmin()) {
            info += ",但由于操作者是管理员，本次操作不进入黑名单";
            cocologger.info(info);
            return;
        }

        cocologger.info(info);

        // 将禁言操作者与群加入黑名单
        PersistenceMapper persistenceMapper = dataApi.getPersistenceMapper();

        AccountMapper accountMapper = persistenceMapper.getAccountMapper();
        GroupMapper groupMapper = persistenceMapper.getGroupMapper();
        TransactionSwitch transactionSwitch = persistenceMapper.getTransactionSwitch();

        // 开启事务，执行操作
        TransactionUtil.run(transactionSwitch, () -> {
            accountMapper.blackOrWhiteAccount(account.getId(), true);
            groupMapper.blackOrWhiteGroup(group.getId(), true);
        });
    }
}
